import axios from 'axios'
import store from '@/store'
import router from "@/router"
import { Message } from 'element-ui'
import ApiResponse from '@/model/ApiResponse.class'
import { isMobile } from '@/tool/util'
import { Toast } from 'vant'

const warnFun = isMobile() ? Toast.fail : Message.error

const exportApi = [
  process.env.VUE_APP_EXPORT_API,
]
const uploadApi = [
  process.env.VUE_APP_UPLOAD_API
]


// axios 配置
axios.defaults.timeout = 10000
// axios.defaults.timeout = 100
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.baseURL = process.env.VUE_APP_BASE_API_URL
axios.defaults.withCredentials = false
// 对响应数据进行处理
axios.interceptors.response.use(
  response => {
    // alert('相应成功')
    const res = new ApiResponse(response)
    setTimeout(() => {
      store.commit('SET_LOADING', false)
    }, 200)
    console.log(response)
    try {
      const code = response.status
      // 请求成功返回response.data
      if (code >= 200 && code < 300) {
        return res.data
      } else {
        return false
      }
    } catch (e) {
      Message.error(e.message)
    }
  },
  error => {
    console.log(error)
    setTimeout(() => {
      store.commit('SET_LOADING', false)
    }, 200)

    if (error.response) {
      switch (error.response.status) {
        case 404:
          warnFun(error.response.data.msg)
          break
        case 401:
          if (!location.hash.includes('login')) {
            if (isMobile()) {
              router.push('/mobile/login')
            } else {
              router.push("/login")
            }
          }
          window.sessionStorage.clear()
          warnFun("登录报错,请联系后台")
          break
        case 500:
          if (error.response?.data?.msg || error.response?.data?.message) {
            // alert('用户登录失败')
            // warnFun(error.response.data.msg || error.response?.data?.message)
          }
          if (!error.response?.data?.msg && !error.response?.data?.message) {
            warnFun('接口参数错误')
          }
          break
        default:
          if (error.response?.data?.msg || error.response?.data?.message) {
            warnFun(error.response.data.msg || error.response?.data?.message)
          }
      }
    }
    return Promise.reject(error)
  }
)

// 设置请求头信息
axios.interceptors.request.use(
  config => {
    store.commit('SET_LOADING', true)
    const token = store.getters.token
    const mobileToken = store.getters.mobileToken.access_token
    const realToken = isMobile() ? mobileToken : token
    if (config.url === '/api-auth/oauth/token') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }

    if (config.url === '/api-taxi/bridge/batchImport') {
      config.headers['Content-Type'] = 'multipart/form-data'
    }

    if (exportApi.includes(config.url)) {
      config.responseType = 'blob'
      // config.timeout = 1000000
    }

    if (realToken) {
      config.headers.Authorization = 'Bearer ' + realToken
    }
    if (uploadApi.includes(config.url)) {
      config.baseURL = process.env.VUE_APP_FILE_API_URL;
      config.headers.Authorization = ''
      console.log(config)
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

export default {
  async get(url, params) {
    return axios.get(url, { params })
  },
  async post(url, params) {
    return axios.post(url, params)
  },
  async delete(url, params) {
    return axios.delete(url, params)
  },
  async put(url, params) {
    return axios.put(url, params)
  }
}
